package absolute_zero.com.urbox;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import absolute_zero.com.urbox.R.drawable;
import absolute_zero.com.urbox.transmition.Client;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.gsm.SmsMessage;
import android.util.Log;
import android.widget.TextView;
public class SMSActivity extends BroadcastReceiver{

	private String IP;

	private SmsMessage[] getMessagesFromIntent(Intent intent) {
		SmsMessage retMsgs[] = null;
		Bundle bdl = intent.getExtras();
		try {
			Object pdus[] = (Object[]) bdl.get("pdus");
			retMsgs = new SmsMessage[pdus.length];
			for (int n = 0; n < pdus.length; n++) {
				byte[] byteData = (byte[]) pdus[n];
				retMsgs[n] = SmsMessage.createFromPdu(byteData);
			}

		} catch (Exception e) {
			Log.e("GetMessages", "fail", e);
		}
		return retMsgs;
	}

	public void onReceive(Context context, Intent intent) {
		Log.d("recieved message", "mesage");
		if (!intent.getAction().equals(
				"android.provider.Telephony.SMS_RECEIVED")) {
			return;
		}
		SmsMessage msg[] = getMessagesFromIntent(intent);
		Log.d("Got the message", "processing");
		for (int i = 0; i < msg.length; i++) {
			String message = msg[i].getDisplayMessageBody();
			if (message != null && message.length() > 0) {
				Log.i("MessageListener:", message);

				// Our trigger message must be generic and human readable because
				// it will end up
				// In the SMS inbox of the phone.
				if (message.startsWith("URBox_IP_request")) {
					  
						Intent accept_intent = new Intent("absolute_zero.com.urbox.urbox_receive");
					Bundle info = new Bundle();
					info.putString("message", message.split("\n")[0]);
					info.putString("address", msg[i].getOriginatingAddress());
					info.putString("file_name", message.split("\n")[1]);
					//Need to get pass person's name and file name
					accept_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 	
					accept_intent.putExtras(info);
					NotificationManager nm = (NotificationManager) context.getSystemService(  
		                     Context.NOTIFICATION_SERVICE);
					Notification notification = new Notification(drawable.urboxicon, "New Package", System.currentTimeMillis());
					
					CharSequence contentTitle = "New Urbox Package";
					CharSequence contentText = message.split("\n")[1] + " from " + msg[i].getOriginatingAddress();
					PendingIntent contentIntent = PendingIntent.getActivity(context, 0, accept_intent, 0);

					notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
					nm.notify(1, notification);

					//context.startActivity(new Intent(accept_intent));
					//start the client to listen for connections
					//Spawns do you want to accept screen
					/*server.start();
					Log.d("Running Server", "started");
					Log.d("Sending IP address", "pre");
					sendIPData(context, intent, msg[i]);*/
				}else if (message.startsWith("UrBox_reponse")){
					//Start icon
					Intent next = new Intent("absolute_zero.com.urbox.TransmitionActivity");
					Bundle info = new Bundle();
					info.putString("message", message);
					info.putString("address", msg[i].getOriginatingAddress());
					next.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 	
					next.putExtras(info);
					NotificationManager response_nm = (NotificationManager) context.getSystemService(  
							                     Context.NOTIFICATION_SERVICE);
					Notification response_notification = new Notification(drawable.urboxicon, "Transferring file", System.currentTimeMillis());
					CharSequence response_contentTitle = "Starting Transfer";
					CharSequence response_contentText = "File Accepted";
					PendingIntent response_contentIntent = PendingIntent.getActivity(context, 0, next, 0);

					response_notification.setLatestEventInfo(context, response_contentTitle, response_contentText, response_contentIntent);
					response_nm.notify(1, response_notification);

					//Write ok status to file
					//Load the file to memory
						File logfile = new File(Environment.getExternalStorageDirectory() + "/urbox/log.txt");
						FileInputStream log_stream = null;
						try {
							log_stream = new FileInputStream(logfile);
						
						BufferedReader buffer = new BufferedReader(new InputStreamReader(log_stream));
						String line = new String();
						String[] parsed_line = new String[3];
						ArrayList<String[]> log_lines = new ArrayList<String[]>();
						
							while((line = buffer.readLine()) !=  null){
								//split on \t and load into an array 
								parsed_line = line.split("\t");
								log_lines.add(parsed_line);
							}
						//Search for line with correct to field
							
							String[] replace = new String[3];
							boolean found = false;
							int j = 0;
							int place = 0;
							for(String[] e: log_lines){
								Log.d("array says", e[0] + " , " + e[1] + " , " + e[2]);
								if(e[1].equals(ContactLookup.numberToName(msg[i].getOriginatingAddress(), context).trim())){
									
									//rewrite line
									replace[0] = e[0];
									replace[1] = e[1];
									replace[2] = "Accepted";
									place = j;
									found = true;
								}
								if(found){
									Log.d("FOund entry", Integer.toString(place));
									found = false;
									log_lines.set(place, replace);
								}else{
									Log.d("We didn't find it boss...", "nada");
								}
								j++;
							}
							//write this to file
							 File newfile = new File(Environment.getExternalStorageDirectory() + "/urbox/log.txt");
							 try{
								 if(newfile.canWrite()){
										FileWriter datawriter = new FileWriter(newfile);
										BufferedWriter out = new BufferedWriter(datawriter);
										for(String[] e: log_lines){
												out.write(e[0] + " \t " + e[1] + " \t " +e[2] + "\n ");
										}
										out.close();
									}
								}catch(IOException e){
									Log.e("Whoops", "Can't write" + e.getMessage());
							 }
							
							
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					//Fire new activity
					Thread client = null;
					try{
						//get filepath from file entitled with person's address
						File f = new File(Environment.getExternalStorageDirectory().getPath() + "/urbox/tmp/" + msg[i].getOriginatingAddress() + ".ubx");
						
						FileInputStream fileIS = new FileInputStream(f);
						BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
						String read = new String();
						while((read = buf.readLine())!= null){
							//Each line will be a path to send...
							client = new Client(read, "10.0.2.2", 8080);
							//is server listening?
						}
						}catch(FileNotFoundException e){
							 Log.d("File Not Found Exception", e.toString());
						}catch(IOException e){
							Log.d("IOException", e.toString());
						}
						//status.setText("Transmission Started. Sending File");
						Log.d("client started", "client");
						client.start();
					
				}else{
					//Do nothing
				}
			}
		}
	}

	public String getIP() {
		return IP;
		
	}

}